<script setup>
import { ElMessage } from "element-plus";
import { getCurrentInstance, onBeforeUnmount, onMounted, ref } from "vue";
import { getToken } from "@/utils/auth";
import { addArticle, getArticleByKey, updArticle, getArticleColumn } from "@/api/article/manage";
import Editor from "@/components/RichText/index.vue";
const { proxy } = getCurrentInstance();
import emitter from "@/utils/mitt";

const formData = ref({
	// 内容栏目id
	articleColumnId: null,
	// 内容内容
	content: "",
	// 内容表-主键id
	id: null,
	// 是否滚动
	isRoll: 0,
	// 是否置顶
	isTop: 0,
	// 是否展示
	isView: 1,
	// 概要
	outline: "",
	// 富文本文件
	richFileIds: [],
	// 内容标题
	title: "",
	// 标题图片
	titleFileIds: [],
	attachFileIds: [],
});
const rules = ref({
	title: [{ required: true, message: "请输入内容标题", trigger: "blur" }],
	articleColumnId: [{ required: true, message: "请选择内容栏目", trigger: "blur" }],
});

const articleColumn = ref([]);
const getArticleColumnList = async () => {
	const res = await getArticleColumn();
	try {
		if (res.code === 200) {
			articleColumn.value = res.data;
		}
	} catch (e) {
		console.log(e);
	}
};
getArticleColumnList();

const fileTitleAction = import.meta.env.VITE_APP_BASE_API + "/article/addTitleImg";

const isFirstPic = ref(false);
const titleFilesData = ref([]);
const richFilesData = ref([]);

const removeFirstPic = () => {
	formData.value.titleFileIds = [];
	titleFilesData.value = [];
	isFirstPic.value = false;
};
const uploadFirstPic = (response, file, fileList) => {
	if (response.code === 200) {
		formData.value.titleFileIds = [response.data.id];
		titleFilesData.value = [response.data];
	}
};

const clearFirstPic = () => {
	formData.value.titleFileIds = [];
	titleFilesData.value = [];
};

const getFormData = () => {
	const tempElement = document.createElement("div");
	formData.value.content = proxy.$refs["editorRef"].getCurrentValue();
	tempElement.innerHTML = formData.value.content;
	const imgElements = tempElement.querySelectorAll("img");
	formData.value.richFileIds = [];
	if (imgElements.length > 0) {
		imgElements.forEach((item) => {
			let itemTemp = richFilesData.value.find((file) => file.accessUrl === item.currentSrc);
			formData.value.richFileIds.push(itemTemp.id);
		});
	}
	return formData.value;
};

const submit = () => {
	proxy.$refs.elForm.validate(async (valid) => {
		if (valid) {
			const params = getFormData();
			if (params.title == null || params.title === "") return;
			if (!isFirstPic.value) params.titleFileIds = [];
			let res;

			params.id !== null && params !== "" ? (res = await updArticle(params)) : (res = await addArticle(params));
			try {
				if (res.code === 200) {
					proxy.$modal.msgSuccess("操作成功");
				} else {
					proxy.$modal.msgError(res.msg);
				}
				formData.value = {
					articleColumnId: null,
					content: "",
					id: null,
					isRoll: 0,
					isTop: 0,
					isView: 1,
					outline: "",
					richFileIds: [],
					title: "",
					titleFileIds: [],
				};
				isFirstPic.value = false;
				titleFilesData.value = [];
				richFilesData.value = [];
				removeFirstPic();
				toList();
			} catch (e) {
				console.log(e);
				proxy.$modal.msgError(JSON.stringify(e));
			}
		}
	});
};

onMounted(() => {
	emitter.on("richTestFileList", (data) => {
		richFilesData.value = [...richFilesData.value, ...data];
		console.log(richFilesData.value);
	});
});

onBeforeUnmount(() => {
	emitter.off("richTestFileList");
});

// 提交完成前往列表
import useTagsViewStore from "@/store/modules/tagsView";
const router = useRouter();
const visitedViews = computed(() => useTagsViewStore().visitedViews);
const thisView = computed(() => visitedViews.value.find((e) => e.name === "ContentAdd"));

function toList() {
	proxy.$tab.closePage(thisView.value).then(() => {
		router.push("/content/contentList");
	});
}
const fileList = ref();
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/article/addAttachFile");

// 上传成功回调
const handleUploadSuccess = (res, file, list) => {
	formData.value.attachFileIds = [];
	if (res.code === 200) {
		ElMessage({
			message: "上传成功",
			type: "success",
		});
		list.forEach((element) => {
			formData.value.attachFileIds.push(element.response.data.id);
		});
	}
};
</script>

<template>
	<div class="dialogContent">
		<div class="section-title">创建内容</div>
		<el-form ref="elForm" :model="formData" :rules="rules" label-width="80px" style="width: calc(100% - 20px)">
			<el-form-item label="内容标题" prop="title" required>
				<el-input v-model="formData.title" clearable placeholder="请输入内容标题"></el-input>
			</el-form-item>
			<el-form-item label="内容概述" prop="outline">
				<el-input
					v-model="formData.outline"
					:autosize="{
						minRows: 3,
					}"
					class="textAreaEdit"
					clearable
					placeholder="请输入内容概述"
					type="textarea"></el-input>
			</el-form-item>
			<el-form-item label="内容栏目" prop="articleColumnId">
				<el-select v-model="formData.articleColumnId" placeholder="请选择内容栏目">
					<el-option v-for="item in articleColumn" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="设置封面">
				<el-switch v-model="isFirstPic" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<el-form-item v-if="isFirstPic" label="内容封面">
				<el-upload
					ref="uploadFirstPicRef"
					:accept="'.jpg,.jpeg,.png'"
					:action="fileTitleAction"
					:headers="{
						Authorization: 'Bearer ' + getToken(),
					}"
					:limit="1"
					:on-remove="removeFirstPic"
					:on-success="uploadFirstPic"
					:show-file-list="false">
					<el-button size="small" type="primary">点击上传</el-button>
					<el-button size="small" type="warning" @click.stop="clearFirstPic">清空上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="isFirstPic && titleFilesData.length > 0" prop="titleFileIds">
				<el-image :preview-src-list="[titleFilesData[0].accessUrl]" :src="titleFilesData[0].accessUrl" style="width: 100px; height: 100px">
				</el-image>
			</el-form-item>
			<el-form-item label="内容内容" prop="content">
				<Editor
					v-model="formData.content"
					:file-size="20"
					:max-height="500"
					:min-height="360"
					:url="'/article/addRichFile'"
					style="width: 100%"
					ref="editorRef" />
			</el-form-item>
			<el-form-item label="上传附件" prop="attachFileIds">
				<el-upload
					v-model:file-list="fileList"
					class="upload-demo"
					:headers="{
						Authorization: 'Bearer ' + getToken(),
					}"
					:action="uploadFileUrl"
					:on-success="handleUploadSuccess"
					multiple>
					<el-button type="primary">点击上传附件</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item label="是否展示" prop="isView">
				<el-switch v-model="formData.isView" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<el-form-item label="是否置顶" prop="isTop">
				<el-switch v-model="formData.isTop" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<!-- <el-form-item label="是否滚动" prop="isRoll">
				<el-switch v-model="formData.isRoll" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item> -->
		</el-form>
		<div class="buttonList">
			<el-button class="button" type="primary" @click="submit">提交</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.dialogContent {
	overflow: auto;
	padding: 10px;
}
.section-title {
	padding: 10px 0px 20px;
	color: #606266;
	font-weight: bold;
}
.buttonList {
	display: flex;
	margin-top: 20px;
	padding-left: 100px;
}
</style>
